<template>
  <div 
    ref="container"
    role="listbox"
    :aria-label="$t('recent_searches')"
    class="search-suggestions-container"
  >
    <transition
      name="fly"
      @enter="handleTransitionEnter"
      @leave="handleTransitionLeave"
    >
      <a-card
        v-if="visible"
        class="suggestions-card"
        :body-style="{ padding: '0' }"
      >
        <!-- 头部 -->
        <div class="suggestions-header">
          <span class="header-text">{{ headerText }}</span>
          <a-button
            v-if="showClearAll"
            type="link"
            @click="handleClearAll"
            class="clear-all-button"
            :aria-label="$t('clear_all_recent_searches')"
          >
            {{ $t('clear_all') }}
          </a-button>
        </div>

        <!-- 建议列表 -->
        <a-list
          :data-source="processedTerms"
          :locale="{ emptyText: '' }"
        >
          <a-list-item
            v-for="(item, index) in processedTerms"
            :key="item.key"
            :class="['suggestion-item', { active: selectedIndex === index }]"
            @click="handleSelect(item.term)"
            @mouseenter="selectedIndex = index"
          >
            <div class="item-content">
              <a-icon type="search" class="search-icon" />
              <span class="term-text">{{ item.term }}</span>
              <a-button
                shape="circle"
                icon="close"
                size="small"
                class="remove-button"
                @click.stop="handleClearSingle(item.term)"
                :aria-label="$t('remove')"
              />
            </div>
          </a-list-item>
        </a-list>
      </a-card>
    </transition>
  </div>
</template>

<script>
import { debounce } from 'lodash';

export default {
  props: {
    id: String,
    searchQuery: String,
    isOpen: Boolean,
    savedTerms: Array
  },
  data() {
    return {
      visible: false,
      selectedIndex: -1,
      scrollPosition: 0
    };
  },
  computed: {
    filteredTerms() {
      const query = this.searchQuery?.toLowerCase() || '';
      return Array.isArray(this.savedTerms)
        ? this.savedTerms.filter(term => typeof term === 'string' && term.toLowerCase().includes(query))
        : [];
    },
    processedTerms() {
      return this.filteredTerms.map((term, index) => ({
        term,
        key: `${this.id}-${index}`
      }));
    },
    showClearAll() {
      return !this.searchQuery;
    },
    headerText() {
      return this.$t('recent_searches').toUpperCase();
    }
  },
  watch: {
    searchQuery: {
      immediate: true,
      handler() {
        this.updateVisibility();
      }
    },
    savedTerms: {
      immediate: true,
      handler() {
        this.updateVisibility();
      }
    }
  },
  methods: {
    updateVisibility() {
      this.visible = this.filteredTerms.length > 0;
      if (this.filteredTerms.length === 0) {
        this.selectedIndex = -1;
      }
    },
    handleTransitionEnter(el) {
      el.style.transform = 'translateY(25px)';
      el.style.opacity = '0';
      requestAnimationFrame(() => {
        el.style.transition = 'all 0.15s ease-out';
        el.style.transform = 'translateY(0)';
        el.style.opacity = '1';
      });
    },
    handleTransitionLeave(el) {
      el.style.transition = 'all 0.15s ease-in';
      el.style.transform = 'translateY(25px)';
      el.style.opacity = '0';
    },
    handleKeyDown: debounce(function(e) {
      if (!this.visible) return;

      switch (e.key) {
        case 'ArrowUp':
          e.preventDefault();
          this.moveSelection(-1);
          break;
        case 'ArrowDown':
          e.preventDefault();
          this.moveSelection(1);
          break;
        case 'Enter':
          this.selectCurrentItem();
          break;
        case 'Escape':
          this.$emit('close');
          break;
      }
    }, 50),
    moveSelection(delta) {
      const maxIndex = this.processedTerms.length - 1;
      let newIndex = this.selectedIndex + delta;

      if (newIndex < 0) newIndex = maxIndex;
      if (newIndex > maxIndex) newIndex = 0;

      this.selectedIndex = newIndex;
      this.scrollToSelected();
    },
    scrollToSelected() {
      this.$nextTick(() => {
        const container = this.$refs.container;
        const items = container.getElementsByClassName('suggestion-item');
        if (items[this.selectedIndex]) {
          items[this.selectedIndex].scrollIntoView({
            behavior: 'smooth',
            block: 'nearest'
          });
        }
      });
    },
    selectCurrentItem() {
      if (this.selectedIndex >= 0) {
        const selectedTerm = this.processedTerms[this.selectedIndex].term;
        this.handleSelect(selectedTerm);
      }
    },
    handleSelect(term) {
      this.$emit('select', term);
      this.resetSelection();
    },
    handleClearAll() {
      this.$emit('clear-all');
      this.resetSelection();
    },
    handleClearSingle(term) {
      this.$emit('clear-single', term);
      this.resetSelection();
    },
    resetSelection() {
      this.selectedIndex = -1;
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
</style>